package com.xuecheng.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.order.utils.PayUtils;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-26
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    OrdersService ordersService;

    @Autowired
    PayUtils payUtils;

    //获取微信支付的请求地址
    @Override
    public ResponseResult<String> createPay(String orderNo) {
        //1.业务判断：查询当前订单是不是初始状态
        LambdaQueryWrapper<Orders> orderQw = new LambdaQueryWrapper<>();
        orderQw.eq(Orders::getOrderNo,orderNo);
        Orders orders = ordersService.getOne(orderQw);
        if (!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //2.业务判断：用户是否已经具有支付信息
        LambdaQueryWrapper<Payment> payQw = new LambdaQueryWrapper<>();
        payQw.eq(Payment::getOrderNo,orderNo);
        Payment payment = this.getOne(payQw);
        //3.构造支付数据，存入到数据库
        if (payment == null) {
            payment = new Payment();
            payment.setUserId(AuthInfoHolder.getUserId());
            payment.setOrderNo(orderNo);
            payment.setCompanyId(orders.getCompanyId());
            payment.setStatus(OrdersConstants.NOT_PAID.toString());
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);
            payment.setTotalAmount(orders.getPrice());
            payment.setCreateDate(new Date());
            boolean save = this.save(payment);
            if (!save) {
                throw new BusinessException(ErrorCode.PAYERROR);
            }
        }
        //4.调用微信生成支付地址
        String url = payUtils.createOrder(orderNo, payment.getTotalAmount(), orders.getCoursePubName());
        //5.构造返回
        return ResponseResult.okResult(url);
    }
}
